/*
 *  Copyright 2016 http://www.kedacomframework.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.kedacom.ctsp.authz.oauth2.service.password;

import com.kedacom.ctsp.authz.oauth2.OAuth2ServerProperties;
import com.kedacom.ctsp.authz.oauth2.configuration.KeyConfiguration;
import com.kedacom.ctsp.authz.oauth2.core.ErrorType;
import com.kedacom.ctsp.authz.oauth2.core.GrantType;
import com.kedacom.ctsp.authz.oauth2.core.JWTConfigProperties;
import com.kedacom.ctsp.authz.oauth2.core.OAuth2Exception;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.entity.Client;
import com.kedacom.ctsp.authz.oauth2.service.AbstractAuthorizationService;
import com.kedacom.ctsp.authz.oauth2.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


/**
 * TODO 完成注释
 *
 * @author
 */
public class DefaultPasswordGranter extends AbstractAuthorizationService implements PasswordGranter {

    @Autowired
    private PasswordService passwordService;
    @Autowired
    private OAuth2ServerProperties serverProperties;
    @Autowired
    private JWTConfigProperties jwtConfigProperties;
    @Autowired
    private KeyConfiguration keyConfiguration;

    @Override
    public AccessToken requestToken(PasswordRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        Set<String> scope = request.getScope();

        assertParameterNotBlank(username, ErrorType.ILLEGAL_USERNAME);
        assertParameterNotBlank(password, ErrorType.ILLEGAL_PASSWORD);

        String userId = passwordService.getUserIdByUsernameAndPassword(username, password);

        assertParameterNotBlank(userId, ErrorType.USER_NOT_EXIST);

        Client client = getClient(request.getClientId(), request.getClientSecret());
        assertGrantTypeSupport(client, GrantType.PASSWORD);
        if (scope == null || scope.isEmpty()) {
            scope = client.getSupportGrantScope();
        }
        if (!client.getSupportGrantScope().containsAll(scope)) {
            throw new OAuth2Exception(ErrorType.SCOPE_OUT_OF_RANGE);
        }

        AccessToken accessToken = accessTokenService.createToken();
        accessToken.setGrantType(GrantType.PASSWORD);
        accessToken.setScope(scope);
        accessToken.setOwnerId(userId);
        accessToken.setExpiresIn(serverProperties.getAccessTokenExpireSeconds());
        accessToken.setClientId(client.getSign());

        accessTokenService.saveOrUpdateToken(accessToken);
        String jwtToken;
        try {
            jwtToken = JWTUtil.generateUserToken(keyConfiguration.getUserPriKey(), username, jwtConfigProperties.getJwtExpire());
        } catch (Exception e) {
            throw new OAuth2Exception(ErrorType.ILLEGAL_JWT_TOKEN);
        }

        accessToken.setJwtToken(jwtToken);
        return accessToken;
    }
}
